package com.monolithiot.sso.controller.front;

import com.monolithiot.sso.common.context.Constants;
import com.monolithiot.sso.common.entity.User;
import com.monolithiot.sso.common.entity.UserGroup;
import com.monolithiot.sso.common.entity.UserGroupRole;
import com.monolithiot.sso.common.exception.AlreadyExistedException;
import com.monolithiot.sso.common.vo.BasicJsonResponse;
import com.monolithiot.sso.common.vo.LayTableResponse;
import com.monolithiot.sso.service.UserGroupRoleService;
import com.monolithiot.sso.service.UserGroupService;
import com.monolithiot.sso.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 2018/12/30 Create by 郭文梁
 * UserGroupController
 * 用户组数据访问控制器
 *
 * @author 郭文梁
 * @date 2018/12/30
 */
@RestController
@RequestMapping("/front/group")
public class UserGroupController {
    private final UserService userService;
    private final UserGroupService userGroupService;
    private final UserGroupRoleService userGroupRoleService;

    @Autowired
    public UserGroupController(UserGroupService userGroupService, UserGroupRoleService userGroupRoleService, UserService userService) {
        this.userGroupService = userGroupService;
        this.userGroupRoleService = userGroupRoleService;
        this.userService = userService;
    }

    /**
     * 获取当前用户加入的用户组
     *
     * @param user 用户
     * @return LayTableResponse
     */
    @GetMapping("mine")
    public LayTableResponse<UserGroupRole> mine(@SessionAttribute(Constants.Key.SESSION_USER) User user) {
        List<UserGroupRole> roles = userGroupRoleService.findByUserWithGroup(user);
        return LayTableResponse.of(roles, (long) roles.size());
    }

    /**
     * 搜索群组
     *
     * @param w 搜索关键字
     * @return LayTableResponse with group list
     */
    @GetMapping("/search")
    public LayTableResponse<UserGroup> search(@RequestParam("w") String w) {
        List<UserGroup> groups = userGroupService.searchByNameOrNumber(w);
        return LayTableResponse.of(groups, (long) groups.size());
    }

    /**
     * 用户申请加入用户组
     *
     * @param user    当前用户 Session中保存
     * @param groupId 用户组ID
     * @return BJR with UserGroupRole
     */
    @PostMapping("/_join")
    public BasicJsonResponse<UserGroupRole> join(@SessionAttribute(Constants.Key.SESSION_USER) User user,
                                                 @RequestParam("groupId") Integer groupId) {
        UserGroup userGroup = userGroupService.get(groupId);
        if (userGroup == null) {
            return BasicJsonResponse.paramError("用户组不存在");
        }
        try {
            UserGroupRole userGroupRole = userGroupRoleService.join(user, userGroup);
            return BasicJsonResponse.ok(userGroupRole);
        } catch (AlreadyExistedException e) {
            return BasicJsonResponse.paramError("您已加入该用户组");
        }
    }

    /**
     * 创建用户组
     *
     * @param user      当前用户
     * @param userGroup 用户组（name,description）
     * @return BJR with UserGroup
     */
    @PostMapping("/_create")
    public BasicJsonResponse<UserGroupRole> create(@SessionAttribute(Constants.Key.SESSION_USER) User user, UserGroup userGroup) {
        userGroup.setCreator(user);
        userGroup.setCreatorId(user.getId());
        UserGroup group = userGroupService.create(userGroup);

        //将群主加入群中
        UserGroupRole role = new UserGroupRole();
        role.setUserGroup(group);
        role.setState(UserGroupRole.STATE_PASS);
        role.setUserId(user.getId());
        role.setUserGroupId(userGroup.getId());
        role.setRoleLevel(UserGroupRole.ROLE_MASTER);
        role.setRoleName(UserGroupRole.ROLE_MASTER_NAME);
        UserGroupRole res = userGroupRoleService.save(role);
        return BasicJsonResponse.ok(res);
    }

    /**
     * 通过用户组号查询用户组详情
     *
     * @param idNumber 用户组号码
     * @return BJR with UserGroup
     */
    @GetMapping("/{idNumber}/detail")
    public BasicJsonResponse<UserGroup> userGroupDetail(@PathVariable("idNumber") String idNumber) {
        UserGroup userGroup = userGroupService.findByIdNumberWithCreator(idNumber);
        if (userGroup == null) {
            return BasicJsonResponse.paramError("用户组不存在");
        }
        return BasicJsonResponse.ok(userGroup);
    }

    /**
     * 获取当前用户可处理的加群申请列表
     *
     * @param user 用户
     * @return 申请列表 by LayTableResponse
     */
    @GetMapping("/apply-list")
    public LayTableResponse<UserGroupRole> applyList(@SessionAttribute(Constants.Key.SESSION_USER) User user) {
        List<UserGroupRole> roles = userGroupRoleService.findNotPassRulesByCreator(user);
        return LayTableResponse.of(roles, (long) roles.size());
    }

    /**
     * 同意用户键入群组
     *
     * @param roleId  申请ID
     * @param creator 当前用户
     * @return BJR with user
     */
    @PostMapping("/_agree-apply")
    public BasicJsonResponse<User> agreeApply(@SessionAttribute(Constants.Key.SESSION_USER) User creator, Integer roleId) {
        UserGroupRole role = userGroupRoleService.get(roleId);
        if (role == null) {
            return BasicJsonResponse.paramError("申请不存在");
        }

        User user = userService.get(role.getUserId());
        UserGroup group = userGroupService.get(role.getUserGroupId());
        if (!group.getCreatorId().equals(creator.getId())) {
            return BasicJsonResponse.paramError("只有群主才有操作权限");
        }

        userGroupRoleService.agreeApply(role);
        return BasicJsonResponse.ok(user);
    }
}
